package com.tianyi.filter;

import com.alibaba.fastjson.JSON;
import com.tianyi.lib.model.WebResult;
import com.tianyi.model.SimpleLoginUser;
import com.tianyi.url.UrlService;
import com.tianyi.util.SimpleUserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * login filter
 *
 * @author cuixuhui
 * @data 2019/11/21
 */
@Component
@Order(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 199)
public class LoginFilter implements Filter {

    @Autowired
    private UrlService urlService;

    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;

        String uri = request.getRequestURI();
        StringBuffer url = request.getRequestURL();

        if (urlService.isExcludeUri(uri)||urlService.isExcludeUrl(Objects.toString(url))){
            //如果是排除的uri就直接过
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        SimpleLoginUser userFromReq = SimpleUserUtils.getUserFromReq(request);
        //登陆的时候 如果从cookie里面拿不到用户的话，重定向到登陆页面
        if (Objects.isNull(userFromReq)){

            //todo 校验用户登陆
            logger.info("login user is null");
//            String toJSONString = JSON.toJSONString(WebResult.error("user need login"));
//            servletResponse.setCharacterEncoding("UTF-8");
//            servletResponse.getWriter().write(toJSONString);
//            HttpServletResponse resp = (HttpServletResponse)servletResponse;
//            resp.setStatus(403);
//            resp.sendRedirect(urlService.getCurrentLoginUrl());
//            return;
        }

        //todo 更新用户时间
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
